/**
 * 
 */

package com.chengyu.eyc.aop;

import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.chengyu.eyc.constant.EycConstants;
import com.chengyu.eyc.model.EycUser;
import com.chengyu.eyc.utils.JWTUtil;

/**
 * @author kevin
 *
 */
@Component
@Aspect
public class SetTokenAspect {

    @AfterReturning(returning = "obj", pointcut = "execution(* com.chengyu.eyc.service.EycServiceImpl.insertUser(..))")
    public void afterReturning(JoinPoint joinPoint, Object obj) {
        if (obj instanceof EycUser) {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes)ra;
            if (sra != null) {
                HttpServletResponse response = sra.getResponse();
                if (response != null) {
                    EycUser eycUser = (EycUser)obj;
                    response.setHeader(EycConstants.TOKEN, JWTUtil.createJWT(eycUser.getUserId()));
                }

            }
        }
    }

}
